package ys.db2es.controller;

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import ys.db2es.pojo.Book;
import ys.db2es.pojo.User;
import ys.db2es.service.UserService;
import ys.db2es.utils.EsUtil;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user2es")
public class User2Es {

    private String index = "user";

    @Resource
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private UserService service;

    @GetMapping("/creatIndex")
    public Object createIndex() throws IOException {
        Map<String, String[]> mapping = new HashMap<>();
        mapping.put("name", new String[]{"type=text", "analyzer=ik_max_word", "index=true", "store=false"});
        mapping.put("password", new String[]{"type=keyword", "store=false"});
        mapping.put("sex", new String[]{"type=keyword"});
        mapping.put("birthday", new String[]{"type=date", "format=yyyy-MM-dd||epoch_millis"});
        mapping.put("registTime", new String[]{"type=date", "format=yyyy-MM-dd hh:mm:ss||epoch_millis"});
        return EsUtil.createIndex(restHighLevelClient, index, 5, 1, mapping);

    }

    @GetMapping("/putDocs")
    public Object putDocs() throws IOException {
        List<User> users = service.findAllUsers();
        return EsUtil.putDocs(restHighLevelClient, index, users);
    }

    @GetMapping("/getAllInEs")
    public Object getAllInEs() throws IOException {
        List<User> users = EsUtil.getAllDocs(restHighLevelClient, index, User.class);
        users.stream().forEach(System.out::println);
        return users;
    }

    @GetMapping("/test")
    public Object testBook() throws IOException {
        return EsUtil.getAllDocs(restHighLevelClient, "book", Book.class);
    }

}
